var ajaxs = function(url, type, param, async, successfuction, dataType, errorMsg, contentType) {
	/*var dt = '';
	if(typeof(dataType) == "undefined" || dataType == '') {
		dt = "json";
	}*/
	if(typeof(contentType) == "undefined" || contentType == '') {
		contentType = "application/x-www-form-urlencoded";
	}

	$.ajax({
		url : url,
		data : param,
		type : type,
		async: async,
		// dataType : dt,
		contentType : contentType,
		success : function(data) {
			if(typeof(successfuction) == "undefined" || successfuction == '') {
				return;
			}
			successfuction(data);
		},
		error : function(XMLHttpReques, massage, errorObject) {
			if(typeof(errorMsg) == "undefined" || errorMsg == '') {
				return;
			}
			layer.alert('失败', { skin: '"layui-bg-red'});
		}
	});
}

/**
 * select2动态搜索数据及回显
 * @param dom
 * @param url
 * @param multiple
 * @param placeable
 */
function initSelect2(dom, url, multiple, placeable) {
    var flag = true;
    if (typeof (placeable) != "undefined") {
        flag = false;
    }
    var subject = $(dom);//元素
    var Select2 = subject.select2({
        ajax: {
            url: url,
            dataType: 'json',
            data: function (params) {
                return {
                    name: params.term // 搜索参数
                };
            },
            processResults: function (data, params) {
                for (var i = 0; i < data.length; i++) {
                    data[i].id = data[i].id;
                    data[i].text = data[i].name;
                }
                return {
                    results: data
                };
            },
            cache: true
        },
        placeholder: flag ? "请输入名称搜索" : placeable,
        allowClear: true,    //选中之后，可手动点击删除
        escapeMarkup: function (markup) {
            return markup;
        }, // 让template的html显示效果，否则输出代码
        minimumInputLength: 1,    //搜索框至少要输入的长度，此处设置后需输入才显示结果
        language: "zh-CN",         //中文
        multiple: multiple, //是否多选
        // maximumSelectionLength: 1,//最多能够选择的个数(后期此处可以用作单选select2的美化)
        width: '100%',
        theme: "classic",
        // closeOnSelect:false,
        templateResult: formatSubject, // 自定义下拉选项的样式模板
        templateSelection: formatSubjectSelection     // 自定义选中选项的样式模板
    });
    return Select2;
};

function formatSubject(item) {
    if (item.loading) return item;
    var markup = '<div> <p style="color: black" class="text-primary">' + item.name|| item.text + '</p>';
    //markup += '这里可以添加其他选项...';
    markup += ' </div>';
    return markup;
}
function formatSubjectSelection(item) {
    return item.name || item.text;
}
//select2回显数据
function echoSelect2(dom,value){
    $.each(value,function(index,value){
        $(dom).append(new Option(value.name, value.id, false, true));
    });
    $(dom).trigger("change");
}

function getBasePath() {
	var location = (window.location+'').split('/');
	var basePath = location[0]+'//'+location[2]+'/'+location[3];
	return basePath;
}

String.prototype.startWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
      return false;
    if(this.substr(0,str.length)==str)
      return true;
    else
      return false;
    return true;
}
String.prototype.endWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
      return false;
    if(this.substring(this.length-str.length)==str)
      return true;
    else
      return false;
    return true;
}

Date.prototype.Format = function(formatStr)
{
    var str = formatStr;
    var Week = ['日','一','二','三','四','五','六'];

    str=str.replace(/yyyy|YYYY/,this.getFullYear());
    str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));

    str=str.replace(/MM/,this.getMonth()>8?(this.getMonth() + 1).toString():'0' + (this.getMonth() + 1));
    str=str.replace(/M/g,this.getMonth()+1);

    str=str.replace(/w|W/g,Week[this.getDay()]);

    str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
    str=str.replace(/d|D/g,this.getDate());

    str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
    str=str.replace(/h|H/g,this.getHours());
    str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
    str=str.replace(/m/g,this.getMinutes());

    str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
    str=str.replace(/s|S/g,this.getSeconds());

    return str;
}

$.FormDialog = function(option) {
	var defaultOpt = {
		form_url : '',
		id: 0,
		title : '',
		save_btn: {show:true, txt:'保存'},
		close_btn: {show:true, txt:'关闭'},
		e_btn : [],          //额外的btn，可选{txt:'123,action:'functionname'}
		callback : null,     //保存成功后的回调函数
		fullscreen : false,
		isclose:false
	}

	var _opt = $.extend({}, defaultOpt, option);

	var init = function() {
		var wdth = _opt.fullscreen ? ' style="width:100%"' : '';
		var htm = '<div class="modal fade" id="im_unique_dlg" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
    				'<div class="modal-dialog" ' + wdth + '>' +
	    				'<div class="modal-content">' +
	    					'<div class="modal-header">' +
	    						'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
	    						'<h4 class="modal-title" id="myModalLabel">' + _opt.title + '</h4>' +
	    					'</div>' +
	    					'<div class="modal-body">' +
	    					'</div>' +
	    					'<div class="modal-footer">' +
	    						(_opt.close_btn.show ? '<button type="button" class="btn btn-default" data-dismiss="modal">' + _opt.close_btn.txt + '</button>' : '') +
	    						(_opt.save_btn.show ? '<button save type="button" class="btn btn-primary">' + _opt.save_btn.txt + '</button>' : '') +
	                		'</div>'+
	                	 '</div>' +
                	  '</div>' +
              	   '</div>';
		$(".form-dialog").html(htm);
		//渲染自定义按钮
		if(!_opt.e_btn) {
			return;
		}
		if(Object.prototype.toString.call(_opt.e_btn)=='[object Array]') {
			//数组
			for(var i in _opt.e_btn) {
				showCustomBtn(_opt.e_btn[i]);
			}
		} else {
			showCustomBtn(_opt.e_btn);
		}
	}

	var showCustomBtn = function(btn) {
		var htm = '<button type="button" class="btn btn-primary">' + btn.txt + '</button>';
		var $htm = $(htm);
		$htm.on('click', function() {
			eval(btn.action + "()");
		});
		$("#im_unique_dlg .modal-footer").append($htm);
	}

	if($(".form-dialog").length < 1) {
		//不存在，新增一个formDialog
		$('body').append("<div class='form-dialog'></div>");
	}
	init();

	//加载form并显示
	var loadForm = function() {
		ajaxs(_opt.form_url, "get", {id:_opt.id}, true, function(data){
			$("#im_unique_dlg .modal-body").html(data);
		}, "html");

		$("#im_unique_dlg").modal({
			keyboard: false,
			backdrop:false
		});
	}

	//绑定保存按钮的事件，自定义的form页面必须要实现一个form_sub的js方法，该按钮默认调用此方法
	$(".form-dialog button[save]").on('click', function() {
		//执行提交
		form_sub();
		//关闭自己
		if(_opt.isclose){
            $("#im_unique_dlg").modal('hide');
		}
		//调用回调函数
		if(_opt.callback) {
			_opt.callback();
		}
	});
	loadForm();
}
$.FormDialg = function(option) {
    var defaultOpt = {
        form_url : '',
        id: 0,
        title : '',
        e_btn : [],          //额外的btn，可选{txt:'123,action:'functionname'}
        callback : null,     //保存成功后的回调函数
        fullscreen : false,
        isclose:false
    }

    var _opt = $.extend({}, defaultOpt, option);

    var init = function() {
        var wdth = _opt.fullscreen ? ' style="width:100%"' : '';
        var htm = '<div class="modal fade" id="im_unique_dlg" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog" ' + wdth + '>' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
            '<h4 class="modal-title" id="myModalLabel">' + _opt.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>' +
            '</div>'+
            '</div>' +
            '</div>' +
            '</div>';
        $(".form-dialog").html(htm);
        //渲染自定义按钮
        if(!_opt.e_btn) {
            return;
        }
        if(Object.prototype.toString.call(_opt.e_btn)=='[object Array]') {
            //数组
            for(var i in _opt.e_btn) {
                showCustomBtn(_opt.e_btn[i]);
            }
        } else {
            showCustomBtn(_opt.e_btn);
        }
    }

    var showCustomBtn = function(btn) {
        var htm = '<button type="button" class="btn btn-primary">' + btn.txt + '</button>';
        var $htm = $(htm);
        $htm.on('click', function() {
            eval(btn.action + "()");
        });
        $("#im_unique_dlg .modal-footer").append($htm);
    }

    if($(".form-dialog").length < 1) {
        //不存在，新增一个formDialog
        $('body').append("<div class='form-dialog'></div>");
    }
    init();

    //加载form并显示
    var loadForm = function() {
        ajaxs(_opt.form_url, "get", {id:_opt.id}, true, function(data){
            $("#im_unique_dlg .modal-body").html(data);
        }, "html");

        $("#im_unique_dlg").modal({
            keyboard: false,
            backdrop:false
        });
    }

    //绑定保存按钮的事件，自定义的form页面必须要实现一个form_sub的js方法，该按钮默认调用此方法
    $(".form-dialog button[save]").on('click', function() {
        //执行提交
        form_sub();
        //关闭自己
        if(_opt.isclose){
            $("#im_unique_dlg").modal('hide');
        }
        //调用回调函数
        if(_opt.callback) {
            _opt.callback();
        }
    });
    loadForm();
}
$.VasFormDialog = function(option) {
    var defaultOpt = {
        form_url : '',
        id: 0,
        title : '',
        e_btn : [],          //额外的btn，可选{txt:'123,action:'functionname'}
        callback : null,     //保存成功后的回调函数
        fullscreen : false,
        isclose:false
    }

    var _opt = $.extend({}, defaultOpt, option);

    var init = function() {
        var wdth = _opt.fullscreen ? ' style="width:100%"' : '';
        var htm = '<div class="modal fade" id="im_unique_dlg" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' +
            '<div class="modal-dialog" ' + wdth + '>' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
            '<h4 class="modal-title" id="myModalLabel">' + _opt.title + '</h4>' +
            '</div>' +
            '<div class="modal-body">' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>' +
            '</div>'+
            '</div>' +
            '</div>' +
            '</div>';
        $(".form-dialog").html(htm);
        //渲染自定义按钮
        if(!_opt.e_btn) {
            return;
        }
        if(Object.prototype.toString.call(_opt.e_btn)=='[object Array]') {
            //数组
            for(var i in _opt.e_btn) {
                showCustomBtn(_opt.e_btn[i]);
            }
        } else {
            showCustomBtn(_opt.e_btn);
        }
    }

    var showCustomBtn = function(btn) {
        var htm = '<button type="button" class="btn btn-primary">' + btn.txt + '</button>';
        var $htm = $(htm);
        $htm.on('click', function() {
            eval(btn.action + "()");
        });
        $("#im_unique_dlg .modal-footer").append($htm);
    }

    if($(".form-dialog").length < 1) {
        //不存在，新增一个formDialog
        $('body').append("<div class='form-dialog'></div>");
    }
    init();

    //加载form并显示
    var loadForm = function() {
        ajaxs(_opt.form_url, "get", {id:_opt.id}, true, function(data){
            $("#im_unique_dlg .modal-body").html(data);
        }, "html");

        $("#im_unique_dlg").modal({
            keyboard: false,
            backdrop:false
        });
    }

    //绑定保存按钮的事件，自定义的form页面必须要实现一个form_sub的js方法，该按钮默认调用此方法
    $(".form-dialog button[save]").on('click', function() {
        //执行提交
        form_sub();
        //关闭自己
        if(_opt.isclose){
            $("#im_unique_dlg").modal('hide');
        }
        //调用回调函数
        if(_opt.callback) {
            _opt.callback();
        }
    });
    loadForm();
}
var d_locale = {
    format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
    applyLabel: '确定', //确定按钮文本
    cancelLabel: '取消', //取消按钮文本
    customRangeLabel: '自定义',
    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
        '七月', '八月', '九月', '十月', '十一月', '十二月'
    ],
    firstDay: 1
}
function dateToMs(date) {
    let result = new Date(date).getTime();
    return result;
}
function msToDate(msec) {
    let datetime = new Date(msec);
    let year = datetime.getFullYear();
    let month = datetime.getMonth();
    let date = datetime.getDate();
    let hour = datetime.getHours();
    let minute = datetime.getMinutes();
    let second = datetime.getSeconds();

    let result1 = year +
        '-' +
        ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
        '-' +
        ((date + 1) < 10 ? '0' + date : date) +
        ' ' +
        ((hour + 1) < 10 ? '0' + hour : hour) +
        ':' +
        ((minute + 1) < 10 ? '0' + minute : minute) +
        ':' +
        ((second + 1) < 10 ? '0' + second : second);

    let result2 = year +
        '-' +
        ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
        '-' +
        ((date + 1) < 10 ? '0' + date : date);

    let result = {
        hasTime: result1,
        withoutTime: result2
    };

    return result;
}

//给数字字符串补零，不支持负数
function padNumber(num, fill) {
    var len = ('' + num).length;
    return (Array(
        fill > len ? fill - len + 1 || 0 : 0
    ).join(0) + num);
}